package pers.corvey.studyjava.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.model.User;
import pers.corvey.studyjava.model.form.RegisterForm;
import pers.corvey.studyjava.model.json.ServerMessageJson;
import pers.corvey.studyjava.service.CaptchaService;
import pers.corvey.studyjava.service.UserService;

@Controller
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CaptchaService captchaService;
    
    @GetMapping
    @ResponseBody
    public ServerMessageJson isAccountExist(@RequestParam("account") String account) {
        ServerMessageJson messageJson = new ServerMessageJson(); 
        if (userService.isAccountExists(account)) {
            messageJson.setMessage("该账号已被注册！");
        } else {
            messageJson.setMessage("该账号可用！");
        }
        return messageJson;
    }
    
    @PostMapping
    @ResponseBody
    public Map<String, Object> createUser(RegisterForm registerForm, HttpSession session) {
        registerForm.validate();
        String correctCaptcha = (String) session.getAttribute("captcha");
        session.removeAttribute("captcha");
        captchaService.checkCaptcha(correctCaptcha, registerForm.getCaptcha());
        User user = registerForm.toUser();
        userService.register(user);
        session.setAttribute("userId", user.getId());
        Map<String, Object> json = new HashMap<>();
        json.put("userName", user.getName());
        return json;
    }
}
